var onClickStrategyName;// 被点击的策略名称，即当前在编辑的策略名称
var isInit = true;
// 第一步，创建计划
$(document).ready(function() {
	// 操作类型
	$('input[name="operType"]').combobox({
		placeholder : "请选择操作类型",
		dataTextField : "name",
		dataValueField : "value",
		setEditable : false,
		value : "0",
		dataSource : [ {
			name : "体检&备份&清理",
			value : "0"
		}, {
			name : "体检&清理",
			value : "1"
		}, {
			name : "体检",
			value : "2"
		}],
		change:change
	});
	function change(){
		var operType = $(this).val();
		if(operType == "2"){
			$("#needCheck").hide();
			$("#analyseFlag").hide();
		}else{
			$("#needCheck").show();
			$("#analyseFlag").show();
		}
		if(typeof(oldOperType) != "undefined" && oldOperType != 0 && operType == 0){
			isAddBack = true;
//				fish.toast('warn', '还未配置目标表信息，请前往配置');
//				return;
		}else{
			isAddBack = false;
		}
		if(!isInit && operType == "0"){// 有备份环节，需要配置目标信息
			fish.toast('warn', '增加备份环节，需要配置目标信息，请前往新增或更新策略');
			$.fn.zTree.init($("#tree"), setting(dmPlanId));
			// 将策略树都改为未配置完整的策略（加一个感叹号）
			// var groupNodes = dmStrategyTreeObj.getNodes();
			// for(var k in groupNodes){
			// 	var nodes = groupNodes[k].children;
			// 	for(var m in nodes){
			// 		$("#" + nodes[m].tId + "_a").append('<span class="text-danger">！</span>');
			// 	}
			// }
		}
		isInit = false;
	};
	
	// 循环周期
	$('input[name="cycleDay"]').spinner({
		min : "1"
	})
	
	// 生失效时间
	$('input[name="effDate"],input[name="expDate"]').datetimepicker({
		buttonIcon : 'calendar',
		viewType:'date',
		format : 'yyyy-mm-dd'
	});
	
	// 开始时间
	$('input[name="startTime"]').datetimepicker({
		//viewType : 'datetime',
		format : 'dd'+'日 '+'hh:ii:ss',
		initialDate:new Date(2016, 4, 1),
		startDate:new Date(2016, 4, 1, 0),
		endDate:new Date(2016, 4, 31, 23, 59),
		container:'#startTimeBox'
	});

	// 执行时间
	$('input[name="cycleType"]').click(function() {
		if (this.value == 0) {
			$('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
				buttonIcon : 'calendar',
				viewType : 'datetime',
				format : 'dd日hh:ii:ss',
				initialDate:new Date(2016, 4, 1),
				startDate:new Date(2016, 4, 1, 0),
				endDate:new Date(2016, 4, 31, 23, 59),
				container:'#startTimeBox',
				autoClose: true
			});
		} else {
			$('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
				buttonIcon : 'time',
				viewType : 'time',
				format : 'hh:ii:ss'
			});
		}
	});
	
	//排除日期
	$('select[name="specialDay"]').multiselect({
		displaySelectedOptions : false // 选中的不再显示在列表
	});
	
	// 源数据类型，选中事件
	$("input[name=sourceType]").click(function() {
		switch ($("input[name=sourceType]:checked").attr("value")) {
		case "1":// 表
			$("#targetType,#analyseFlag").show();
			break;
		case "2":// 文件
			$("#targetType,#analyseFlag").hide();
			break;
		default:
			break;
		}
	});
	
	function execTypeShow(){
		switch ($("input[name=execType]:checked").attr("value")) {
		case "1":// 自动执行
			if($("input[name=execFrequency]:checked").attr("value") == "1"){// 执行频率：单次执行
				$("#execFrequency,#startTime").show();
			}else{
				$("#execFrequency,#cycleType,#startTime,#specialDay").show();
			}
			break;
		case "2":// 手动执行
			if($("input[name=execFrequency]:checked").attr("value") == "1"){// 执行频率：单次执行
				$("#execFrequency,#startTime").hide();
			}else{
				$("#execFrequency,#cycleType,#startTime,#specialDay").hide();
			}
			break;
		default:
			break;
		}
	};
	execTypeShow();
	
	// 执行方式，选中事件
	$("input[name=execType]").click(function(){
		execTypeShow();
	});
	
	function execFrequencyShow(){
		switch ($("input[name=execFrequency]:checked").attr("value")) {
		case "0":// 循环执行
			$("#cycleType,#specialDay").show();
			$('input[name=cycleDay]').attr('data-rule','required; integer; range[1~1000]');
			break;
		case "1":// 单次执行
			$("#cycleType,#specialDay").hide();
			$("input[name=cycleDay]").attr('data-rule','').resetValid();
			// 选择日期
			$($('input[name="cycleType"]')[0]).prop('checked',true);
			$('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
				buttonIcon : 'calendar',
				viewType : 'datetime',
				format : 'dd日hh:ii:ss',
				initialDate:new Date(2016, 4, 1),
				startDate:new Date(2016, 4, 1, 0),
				endDate:new Date(2016, 4, 31, 23, 59),
				container:'#startTimeBox',
				autoClose: true
			});
			break;
		default:
			break;
		}
	};
	execFrequencyShow();
	
	// 执行频率，选中事件
	$("input[name=execFrequency]").click(function(){
		execFrequencyShow();
	});
	
	// 所属系统，下拉树
	var nodeId_setting = {
		async: {
			enable: true,
			contentType: "application/json",
			url: webRoot + 'common/sysModule/queryAllForTree.do',
			type: 'post'
		},
		view: {
			dblClickExpand:false,
			selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
		},
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pId",
				rootPId: 0
			}
		},
		callback: {
			onClick: nodeIdonClick,
			onAsyncSuccess: edit
		}
	};
	
	var nodeIdTree = $.fn.zTree.init($("#nodeId_tree"), nodeId_setting);
	var nodeIdTreeObj = $.fn.zTree.getZTreeObj("nodeId_tree");
	function nodeIdonClick(){
		nodes = nodeIdTree.getSelectedNodes();
		var nodeIdInput = $('input[name="nodeId"]');
		// 设置控件的其他属性：vId，为真正的value
		nodeIdInput.attr("vId",nodes[0].id).val(nodes[0].name);
		hideNodeIdTree();
	};
	//下拉树相对位置，随着窗口联动
	function nodeIdTreePos(){
   		var inputObj = $('input[name="nodeId"]');
        var inputObjOffSet = $('input[name="nodeId"]').offset();
            var $treePs = $("#nodeId_commbox_tree").css({left:inputObjOffSet.left + "px", top:inputObjOffSet.top + inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
            return $treePs;
            }
	$('input[name="nodeId"]').click(function(){
		nodeIdTreePos().slideDown("fast");
        $(window).resize(function(){
			nodeIdTreePos();
        });
        $("body").bind("mousedown", onBodyDownNode);
	});
	function onBodyDownNode(event) {
		if (!(event.target.name == "nodeId" || event.target.id == "nodeId_commbox_tree" || $(event.target).parents("#nodeId_commbox_tree").length>0)) {
			hideNodeIdTree();
		}
	};
	function hideNodeIdTree(){
		$("#nodeId_commbox_tree").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownNode);
	};
	
	// 策略树 相关
	function zTreeBeforeDrag(treeId, treeNodes) {
	    return false;
	};
	setting = function setting(n){
		var setting = {
			async: {
				enable: true,
				contentType: "application/json",
				url: webRoot + 'baseconfig/dmstrategy/queryRecordList.do?dmPlanId=' + n,
				type: 'post'
			},
			view: {
				dblClickExpand:false,
				selectedMulti: false,
				showIcon: false,
				addDiyDom:addDiyDom
			},
			edit: {
				drag:{
					isCopy:false,
					autoOpenTime:100
				},
				enable: true
			},
			data: {
				keep:{
					leaf:true,
					parent:true
				},
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pId",
					rootPId: 0
				}
			},
			callback: {
				beforeDrag: beforeDrag,
				beforeDrop: beforeDrop,
				beforeAsync: beforeAsync,
				beforeRemove: beforeRemove,
				onClick: onClick,
				onNodeCreated: zTreeOnNodeCreated
			}
		};
		return setting;
	}
	$.fn.zTree.init($("#tree"), setting(dmPlanId));
	var treeObj = $.fn.zTree.getZTreeObj("tree");
	dmStrategyTreeObj = $.fn.zTree.getZTreeObj("tree");
	var newCount = 1, expandAll=true;

	// 用于捕获节点生成 DOM 后的事件回调函数
	function zTreeOnNodeCreated(event, treeId, treeNode){
		if(isAddBack && treeNode.pId != 0){// 说明不是策略组
			for(var k in targetTableIsOKs){
				if(targetTableIsOKs[k].name == treeNode.name){// 已经添加过
					return;
				}
			}
			var targetTableIsOK = {};
			targetTableIsOK.name = treeNode.name;
			targetTableIsOK.isOK = 0;
			targetTableIsOKs.push(targetTableIsOK);
		}
	}

	// 拖动之前
	function beforeDrag(treeId, treeNodes) {
		for (var i=0; i<treeNodes.length; i++) {
			// 禁止根节点拖拽
			if (treeNodes[i].drag === false) {
				return false;
			}
		}
		return true;
	}

	// 放下之前
	// treeNodes：移动的策略；targetNode：目标策略；moveType：prev-移动到目标前面，next-移动到目标后面
	// inner:移动到策略组
	function beforeDrop(treeId, treeNodes, targetNode, moveType) {
		//禁止成为根节点
		if(targetNode == null || (moveType != "inner" && !targetNode.parentTId)){
			return false;
		}else{
			$.blockUI({message : "数据载入中,请稍候..."});
			$.ajax({
				url : webRoot + 'baseconfig/dmstrategy/drag.do',
				type : 'POST',
				async : true,
				data : {moveId: treeNodes[0].id, targetId: targetNode.id, moveType: moveType}
			}).done(function(serverData, textStatus, jqXHR) {
				$.fn.zTree.init($("#tree"), setting(dmPlanId));
			}).fail(function() {
				fish.toast('error', '网络连接失败！');
			}).always(function() {
				$.unblockUI();
			});
		}
	}

	function beforeAsync(treeId, treeNode){
		if(treeNode && !treeNode.parentTId) return false;
	}

	/**
	 * 策略组号：treeNode.id
	 */
	// 添加策略 按钮事件
	function addDiyDom(treeId, treeNode) {
		// 添加策略 按钮事件
		var aObj = $("#" + treeNode.tId + "_a");
		if(treeNode.isParent){
			var AddBtnStr = '<button id="addLeafNode_'+treeNode.id+'" class="addLeafNode pull-right">添加策略</button>';
			aObj.after(AddBtnStr);
			var btn = $("#addLeafNode_"+treeNode.id);
			if (btn) btn.bind("click", function(){
				dmStrategyGroupNum = treeNode.id;
				// srcTableDraft = false;
				$('#planForm').validator({
					timely:0,
					ignore:':hidden'//任何不可见的元素，都不作验证
				});
				// 验证计划信息的输入
				if ($("#planForm").isValid()) {
					if(isAddBack){
						onClickStrategyName = '-1';
					}
					dmStrategyId = 0;
					// 更改为新增状态
					act = "add";
					isEdit = 0;
					isFirst = true;
					// 表单数据-计划信息
					if(!getPlanFormData()) return;
					// 隐藏显示步骤
					$('#firstStep').addClass("hidden");
					$('#secondStep').removeClass("hidden");
					// 只做体检时隐藏归档上限
					if(planFormData.operType=="2"){
						$('#upperCnt').addClass("hidden");
					}else{
						$('#upperCnt').removeClass("hidden");
					}
					$('.step-ing .st2').addClass('st2On')
					// 隐藏显示底部按钮
					$('#button-prov').removeClass("hidden");
					$('#button-next').removeClass("hidden");
					$('#button-add-strategy').addClass("hidden");
					$('#button-submit').addClass("hidden");
					// 清空后面几步骤的信息
					// 清空第二步的表单信息
					resetSrcTableForm();
					// 清空第三步的表单信息
					resetTargetTableForm();
					// 清空第四步的表单信息
					$('#conditionForm textarea').val('');
					oldSelectCondition = "";
					// 脚本验证字段
					scriptVerifyIsOK = false;
				}else{
					setTimeout(function(){$('#planForm').validator('cleanUp')},3000);
				}
			});
		}
		if(treeNode.threads) {
			aObj.append('<span style="color:#999">(并发数：'+treeNode.threads+')</span>');
		}
		// if(treeNode.state == "00D"){
		// 	// aObj.append('<span class="text-danger">！</span>');
		// 	// planSubmit = false;
		// 	// showSubmitOnPlan(planSubmit);
		// }else{
			if(isAddBack && treeNode.pId != 0){
				for(var k in targetTableIsOKs){
					if(targetTableIsOKs[k].isOK == 0){
						// aObj.append('<span class="text-danger">！</span>');
						planSubmit = false;
						showSubmitOnPlan(planSubmit);
					}
				}
			}
		// }
	};
	
	// 策略 按钮事件
	function onClick(eventjs, treeIdString, treeNodeJSON, clickFlag){
		if(treeNodeJSON.isParent){
			return;
		}
		if(!getPlanFormData()) return;
		$('#firstStep').addClass("hidden");
		$('#secondStep').removeClass("hidden");
		// 只做体检时隐藏归档上限
		if(planFormData.operType=="2"){
			$('#upperCnt').addClass("hidden");
		}else{
			$('#upperCnt').removeClass("hidden");
		}
		$('.step-ing .st2').addClass('st2On')
		// 隐藏显示底部按钮
		$('#button-prov').removeClass("hidden");
		$('#button-next').removeClass("hidden");
		$('#button-add-strategy').addClass("hidden");
		$('#button-submit').addClass("hidden");
		// 清空第二步的表单信息
		resetSrcTableForm();
		// 给表单控件赋值
		$.blockUI({message : "数据载入中,请稍候..."});
		$.ajax({
			url : webRoot + 'baseconfig/dmstrategy/getStrategyAllInfo.do',
			type : 'POST',
			async : true,
			data : {dmStrategyId: treeNodeJSON.id}
		}).done(function(serverData, textStatus, jqXHR) {
			// onClickNodeTid = treeNodeJSON.id;
			isFirst = true;
			if(typeof(oldOperType) != "undefined" && oldOperType != 0 && planFormData.operType == 0){
				isAddBack = true;
			}else{
				isAddBack = false;
			}
			// if(serverData.state == "00D"){
			// 	isDraft = true;
			// }else{
			// 	isDraft = false;
			// }
			dmStrategyId = serverData.dmStrategyId;
			dmStrategyGroupNum = treeNodeJSON.pId;
			// 策略相关的数据回绑
			setStrategyInfo(serverData);
			setRefTableInfo(serverData);
			// 脚本验证字段
			scriptVerifyIsOK = false;
			// 判断当前策略是否配置好目标信息
			if(isAddBack){
				onClickStrategyName = treeNodeJSON.name;
			}
		}).fail(function() {
			fish.toast('error', '网络连接失败！');
		}).always(function() {
			$.unblockUI();
		});
	};
	
	// 删除策略 按钮事件
	function beforeRemove(treeId, treeNode){
		fish.confirm("这将会直接删除策略，确定删除?").result.then(function(){
			if(treeNode.isParent){// 删除整个策略组
				$.blockUI({message : "数据载入中,请稍候..."});
				$.ajax({
					url : webRoot + 'baseconfig/dmstrategy/deleteGroup.do',
					type : 'POST',
					async : true,
					data : {dmStrategyId: treeNode.id, dmPlanId: dmPlanId}
				}).done(function(serverData, textStatus, jqXHR) {
					$.fn.zTree.init($("#tree"), setting(dmPlanId));
				}).fail(function() {
					fish.toast('error', '网络连接失败！');
				}).always(function() {
					$.unblockUI();
				});
			}else{
				$.blockUI({message : "数据载入中,请稍候..."});
				$.ajax({
					url : webRoot + 'baseconfig/dmstrategy/delete.do',
					type : 'POST',
					async : true,
					data : {dmStrategyId: treeNode.id, dmPlanId: dmPlanId}
				}).done(function(serverData, textStatus, jqXHR) {
					$.fn.zTree.init($("#tree"), setting(dmPlanId));
				}).fail(function() {
					fish.toast('error', '网络连接失败！');
				}).always(function() {
					$.unblockUI();
				});
			}
		});
	};
	
	// 添加策略组 按钮事件
	$("#addParentNode").click(function() {
		$('#planForm').validator({
			timely:0,
			ignore:':hidden'//任何不可见的元素，都不作验证
		});
		// 验证输入值的正确性
		if ($("#planForm").isValid()) {
			// 表单数据-计划信息
			if(!getPlanFormData()) return;
			var TreeNodes = treeObj.getNodes();
			for(var i=0;i<TreeNodes.length;i++){
				if(TreeNodes[i].isParent){
					if(TreeNodes[i].children == undefined){
						fish.toast('warn', '已存在未配置的策略组！');
						return;
					}
				}
			}
			$.blockUI({message : "缓存策略信息,请稍候..."});
			$.ajax({
				url : webRoot + 'baseconfig/dmstrategy/addStrategyGroup.do',
				type : 'POST',
				async : true,
				data : planFormData
			}).done(function(serverData, textStatus, jqXHR) {
				if(serverData.dmPlanId == -1){
					fish.toast('warn', '存在相同的计划名称，请重新输入计划名称');
					return;
				}
				dmPlanId = serverData.dmPlanId;
				dmStrategyGroupNum = serverData.groupNbr;
				dmStrategyId = 0;
				treeObj.addNodes(null,{id: serverData.groupNbr, pId:0, name: serverData.groupName, open:true, drag:false,isParent:true},false);
			}).fail(function() {
				fish.toast('error', '网络连接失败！');
			}).always(function() {
				$.unblockUI();
			});
		}else{
			setTimeout(function(){$('#planForm').validator('cleanUp')},3000);
		}
	});

	$('#expandAllNode').bind('click',function(){
		if(expandAll){
			 treeObj.expandAll(false);
			$(this).html('展开全部');
			return expandAll=false;
		}else{
			 treeObj.expandAll(true);
			$(this).html('收起全部');
			return expandAll=true;
		}
	})
});

// 策略相关的数据回绑
function setStrategyInfo(serverData){
	act = "edit";
	dmStrategyPO = serverData;
	var dmSrcTablePO = serverData.dmSrcTablePO;
	// 设置源表信息
	setSrcTableInfo(dmSrcTablePO);
	//setInfo(serverData);
	// 配置目标数据
	dmTargetTablePOList = dmStrategyPO.dmTargetTablePOList;
	// if(dmStrategyPO.state == "00A"){
		tableNum = dmStrategyPO.dmTargetTablePOList.length;
		for(var i = 0; i < tableNum; i++){
			columnsRelationsIsOK.push(1);
		}
		var j;
		for(var i = 0; i < tableNum; i++){
			j = i + 1;
			newTargetTable(dmStrategyPO.dmTargetTablePOList[i], j);
			// 数据库下拉树
			$('input[name="' + targetTableDbLinkId_name + j + '"]').attr("vId",dmStrategyPO.dmTargetTablePOList[i].dbLinkId);
			$('input[name="' + targetTableDbLinkId_name + j + '"]').val(dmStrategyPO.dmTargetTablePOList[i].dbUserName);
			var treeObj = $.fn.zTree.getZTreeObj(targetTableDbLinkIdTree_id + j);
			var parentNode = treeObj.getNodeByParam("id", dmStrategyPO.dmTargetTablePOList[i].dbLinkId, null);
			var node = treeObj.getNodeByParam("name", dmStrategyPO.dmTargetTablePOList[i].dbUserName, parentNode);
			treeObj.selectNode(node, false);
		}
	// }
	setSelConditionInfo(dmSrcTablePO);
	oldSelectCondition = dmSrcTablePO.selectCondition;
}

// 策略相关的数据回绑
function setRefTableInfo(dmStrategyPO){
	// 设置源表信息targetColMaps
	// 配置目标数据
	var targetTableNum = dmStrategyPO.dmTargetTablePOList.length;
	for(var i = 0; i < targetTableNum; i++){
		var rs = [];
		rs.push(i+1);
		var targetTablePo = dmStrategyPO.dmTargetTablePOList[i];
		for(var j = 0;j<targetTablePo.hasOkColumnsRelationPOList.length;j++ ){
			var columnsRel = targetTablePo.hasOkColumnsRelationPOList[j];
			rs.push(columnsRel.type+','+columnsRel.src+','+columnsRel.target);
		}
		targetColMaps[i] = rs;
	}
	columnsRelationsIsOK = [];
	for(var i = 0; i < targetColMaps.length; i++){
		columnsRelationsIsOK.push(1);
	}
}

// 获取表单数据-计划信息
function getPlanFormData(){
	// 表单数据-计划信息
	planFormData = $("#planForm").form("value");
	// 计划ID
	planFormData.dmPlanId = dmPlanId;
	planFormData.dmStrategyId = dmStrategyId;
	// 操作用户
	planFormData.staffId = staffId;
	// 重组排除日期，用","隔开
	if(planFormData.specialDay != null&&$.type(planFormData.specialDay) === "array"){
		planFormData.specialDay=planFormData.specialDay.join(',');
	}
	// 判断生失效时间
	if(planFormData.expDate <= planFormData.effDate && planFormData.expDate != "" && planFormData.effDate != ""){
		fish.toast('warn', "失效时间不能小于生效时间");
		return false;
	}
	// 判断执行时间是不是在生失效时间之内
	var expDate = planFormData.expDate.replace('-','/').replace('-','/');
	var effDate = planFormData.effDate.replace('-','/').replace('-','/');
	var a = (Date.parse(expDate) - Date.parse(effDate)) / 3600 / 1000 / 24;
	if(planFormData.execType == 1 && planFormData.execFrequency == 0 && planFormData.cycleType == 0 && a < 31){// 按月循环
    	fish.toast('warn', "按月循环的计划，生失效时间必须大于31天");
    	return false;
	}
	var expYear = planFormData.expDate.split(" ")[0].split("-")[0];
	var effYear = planFormData.effDate.split(" ")[0].split("-")[0];
	var expMonth = planFormData.expDate.split(" ")[0].split("-")[1];
	var effMonth = planFormData.effDate.split(" ")[0].split("-")[1];
	var expDay = planFormData.expDate.split(" ")[0].split("-")[2];
	var effDay = planFormData.effDate.split(" ")[0].split("-")[2];
	var startDay = planFormData.startTime.split(" ")[0].substring(8,10);
	if(planFormData.execFrequency == 1 && planFormData.execType == 1 && a < 31){// 单次执行、自动执行、生失效时间间隔不足一个月
		if(effMonth < expMonth || effYear < expYear){
			if(startDay < effDay && startDay > expDay){
				fish.toast('warn', "执行时间要在生失效时间内");
				return false;
			}
		}else if(effMonth == expMonth){
			if(startDay < effDay || startDay > expDay){
				fish.toast('warn', "执行时间要在生失效时间内");
				return false;
			}
		}
	}
	planFormData.nodeId = $('input[name="nodeId"]').attr("vId");
	if(planFormData.operType == 2){
		planFormData.needCheck = "F";
	}
	if(planFormData.execType == 2 || planFormData.execFrequency == 1){
		planFormData.cycleDay = null;
	}
	return true;
}